<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<script src="/node_modules/axios/dist/axios.js"></script>
	<link rel="stylesheet" href="/node_modules/bootstrap/dist/css/bootstrap.min.css">
	<title>购物车</title>
</head>

<body>
	<div id="app">
		<div class="container">
			<p class="h2 text-primary text-center">购物车页面</p>
			<div class="row">
				<table class="table table-bordered">
					<thead>
						<th>全选 &nbsp;&nbsp;<input type="checkbox" v-model="checkAll" @change='getStatus'/></th>
						<th>商品</th>
						<th>单价</th>
						<th>数量</th>
						<th>小计</th>
						<th>操作</th>
					</thead>
					<tbody>
						<tr v-for="(item,index) in products">
							<td><input type="checkbox" v-model="item.isSelected"  @change="getStatusOne" ></td>
							<td>
								<img :src="item.productImg" alt="">
								<span class="small text-info">{{item.productName}}</span>
							</td>
							<td class="text-center text-success">{{ item.productPrice}}</td>
							<td class="text-center text-success"><input type="number" class="small" v-model.number="item.productCount" min="1" max="100"></td>
							<td> {{ item.productPrice*item.productCount  | toFixed(2)}} </td>
							<td><button class="btn-danger" @click="remove(index)">删除</button></td>
						</tr>
						<tr> 
							<td colspan="6"> 总计：{{sum | toFixed(2)}}</td>
					  </tr>
					</tbody>
				</table>
				<!-- {{msg}} -->
			</div>
		</div>
	</div>

	<script src="/node_modules/vue/dist/vue.js"></script>
	<script>
		const vm = new Vue({
			el: '#app',
			data: {
				products:[],
				msg:'hello',
				checkAll:false
			},
			created(){ // 页面一加载就那数据
				this.initData()
			},
			computed:{
				sum(){
					return this.products.reduce((pre, next) =>{
						// 如果当前没被选中，则返回上次的pre ，不加当前这一项
						if (next.isSelected !==true ) return pre 
						return pre + next.productCount * next.productPrice
					},0)
				}
			},
			methods: {
				initData(){ // 数据初始化
					// 发送请求获取数据
					axios.get('./data/data.json')
					.then(res =>{
						// console.log(res)
						if (res.status !== 200) return alert('数据获取失败!')
						this.products = res.data
						this.getStatusOne()
						// this.isSelected.push(res.data.isSelected)
					})
				},
				remove(i){ // 删除该香
					// console.log('ok')
					this.products =	this.products.filter((item,index)=>{
						return index!== i
					})
				},
				getStatus(){
					this.products.forEach( item => item.isSelected = this.checkAll)
				},
				getStatusOne(){
					this.checkAll = this.products.every((item) => item.isSelected === true )
				}
			},
			filters:{
				toFixed:(data,num) =>{
					return parseFloat(data).toFixed(num)
				}
			}
		})
	</script>
</body>

</html>